package control;

import entity.Category;
import entity.Product;
import entity.ProductAvailability;
import java.io.IOException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import utils.ServletUtil;

@WebServlet(name="EditProduct", urlPatterns={"/backend/EditProduct"})
public class EditProduct extends HttpServlet {
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        boolean formSucces = false;
        Product product = null;
        
        EntityManagerFactory fact = Persistence.createEntityManagerFactory("vh11i_jeePU");
        EntityManager em = fact.createEntityManager();
        
        try {
            // Zoek het product via id (staat in de querystring)
            long productId = ServletUtil.getLong(request.getParameter("product_id"), -1);
            product = em.find(Product.class, productId);
            request.setAttribute("product", product);
            
            if (product != null) {
                // Haal de categorieen op voor de selectbox
                Query query = em.createNamedQuery("allCategories", Category.class);
                List<Category> categories = query.getResultList();
                request.setAttribute("categories", categories);
                
                if(request.getMethod().equals("POST")) {
                
                    // Zoek de gekozen categorie op
                    long categoryId = ServletUtil.getLong(request.getParameter("categoryId"), -1);
                    Category category = em.find(Category.class, categoryId);

                    // Parse de prijs
                    double price = ServletUtil.getDouble(request.getParameter("price"), 0);

                    // Haal de beschikbaarheid Enum op
                    int ordinal = ServletUtil.getInt(request.getParameter("availability"), 0);
                    ProductAvailability availability = ProductAvailability.values()[ordinal];
                    
                    // Wijzig de product bean
                    product.setName(request.getParameter("name"));
                    product.setCategory(category);
                    product.setAvailability(availability);
                    product.setDescription(request.getParameter("description"));
                    product.setPrice(price);
                    
                    // Valideer de bean
                    if (product.getName().length() > 0) {
                        // Sla de bean op
                        em.getTransaction().begin();
                        em.persist(product);
                        em.getTransaction().commit();
                        formSucces = true;
                    }
                }
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        finally {
            em.close();
            fact.close();
        }
        
        if (formSucces) {
            response.sendRedirect("EditProduct?success=true&category_id=" + product.getCategory().getId());
        }
        else {
            RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/editProduct.jsp");
            dispatcher.forward(request, response);
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
